/*
 * Copyright 2013 JROSE
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jrose.core.jdbc.entity.field;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jrose.core.jdbc.entity.field.internal.PrimaryKeyField;
import org.jrose.core.util.AnnotationUtils;
import org.jrose.core.util.FieldAccessor;
import org.springframework.util.Assert;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

@Slf4j
abstract public class PersistenceField<A extends Annotation> extends FieldAccessor {
    @Getter private final A annotation;
    @Getter private final String columnName;
    @Getter(AccessLevel.PROTECTED) private final Set<Class<?>> restrictedFieldTypes;

    protected PersistenceField(Class<?> clazz, Field field, A annotation) {
        super(clazz, field);
        Assert.notNull(annotation);

        this.annotation = annotation;
        this.columnName = initializeColumnName();

        RestrictedFieldTypes restrictedFieldTypes = AnnotationUtils.getAnnotation(getClass(), RestrictedFieldTypes.class);
        Assert.notNull(restrictedFieldTypes);
        this.restrictedFieldTypes = new HashSet<>();
        this.restrictedFieldTypes.addAll(Arrays.asList(restrictedFieldTypes.value()));

        // valite current field if necessary
        if (isAutoIncField()) {
            Assert.isTrue(getFieldType() == Long.class || getFieldType() == Integer.class);
        }
        if (!this.restrictedFieldTypes.isEmpty()) {
            if (getFieldType().isEnum()) {
                Assert.isTrue(this.restrictedFieldTypes.contains(Enum.class));
            } else {
                Assert.isTrue(this.restrictedFieldTypes.contains(getFieldType()));
            }
        }
    }

    public boolean isPrimaryKeyField() {
        return getClass() == PrimaryKeyField.class;
    }

    public boolean isEnumField() {
        return getFieldType().isEnum();
    }

    public boolean isAutoIncField() {
        return false;
    }

    public void prepareDefaultValue(Object obj) {
        Assert.notNull(obj);
    }

    // Private method:

    private String initializeColumnName() {
        String defaultName;
        try {
            Method method = annotation.getClass().getMethod("name");
            defaultName = (String) method.invoke(annotation);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ex) {
            throw new RuntimeException(ex.getMessage(), ex);
        }
        if (StringUtils.isNotBlank(defaultName)) {
            return defaultName;
        }
        StringBuilder generatedColumnName = new StringBuilder();
        for (char c : getFieldName().toCharArray()) {
            if (Character.isUpperCase(c)) {
                if (generatedColumnName.length() != 0) {
                    generatedColumnName.append('_');
                }
            }
            generatedColumnName.append(Character.toUpperCase(c));
        }
        return generatedColumnName.toString();
    }
}
